﻿using MyToDo.Common;
using MyToDo.Common.Models;
using MyToDo.Extensions;
using MyToDo.Service.ToDo;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls.Primitives;

namespace MyToDo.ViewModels
{
    public class ToDoViewModel: NavigationViewModel
    {
        public DelegateCommand<string> ExecuteCommand { get; private set; }
        public DelegateCommand<ToDoDto> SelectedCommand { get; private set; }
        public DelegateCommand<ToDoDto> DeleteCommand { get; private set; }
        
        private readonly IToDoService service;
        private readonly IDialogHostService dialogHost;

        public ToDoViewModel(IToDoService service,IContainerProvider containerProvider):base(containerProvider)
        {
            this.service = service;
            ToDoDtos = new ObservableCollection<ToDoDto>();
            //CreateToDoList();
            //CreateToDoListService();
            ExecuteCommand = new DelegateCommand<string>(Execute);
            SelectedCommand = new DelegateCommand<ToDoDto>(Selected);
            DeleteCommand = new DelegateCommand<ToDoDto>(Delete);
            dialogHost = containerProvider.Resolve<IDialogHostService>();
        }        

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增":
                    Add();
                    break;
                case "查询":
                    CreateToDoListService();
                    break;
                case "保存":
                    Save();
                    break;
            }
        }
        private async void Delete(ToDoDto dto)
        {
            try
            {
                var dialogResult = await dialogHost.Question("温馨提示",$"确认删除待办事项：{dto.Title}?");
                if (dialogResult.Result != Prism.Services.Dialogs.ButtonResult.OK) return;
                UpdateLoading(true);
                var deleteResult = await service.DeleteAsync(dto.Id);
                if (deleteResult.Status)
                {
                    var todo = ToDoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                    if (todo != null)
                    {
                        ToDoDtos.Remove(todo);
                    }
                }
            }
            finally{
                UpdateLoading(false);
            }
        }


        private string search;

        public string Search
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }

        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set { selectedIndex = value; RaisePropertyChanged(); }
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            if(navigationContext.Parameters.ContainsKey("Value"))
                SelectedIndex = navigationContext.Parameters.GetValue<int>("Value");
            CreateToDoListService();
        }
        async void CreateToDoListService()
        {
            UpdateLoading(true);

            ToDoDtos.Clear();

            int? Status = SelectedIndex == 0 ? null : SelectedIndex == 1 ? 1 : 0;
            var todoResult = await service.GetAllFilterAsync(new Service.Model.ToDoParameter()
            {
                PageIndex = 0,
                PageSize = 100,
                Search = Search,
                Status = Status
            });
            if (todoResult.Status)
            {
                foreach (var item in todoResult.Result.Items)
                {
                    ToDoDtos.Add(item);
                }
            }

            UpdateLoading(false);
        }
        private bool isRightDrawerOpen;
        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set { isRightDrawerOpen = value; RaisePropertyChanged(); }
        }
        private ToDoDto currentDto;

        public ToDoDto CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }

        private void Add()
        {
            CurrentDto = new ToDoDto();
            IsRightDrawerOpen = true;
        }
        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(CurrentDto.Title) || string.IsNullOrWhiteSpace(CurrentDto.Content))
                return;
            UpdateLoading(true);
            try {
                if (CurrentDto.Id > 0)
                {
                    var updateResult = await service.UpdateAsync(CurrentDto);
                    if (updateResult.Status)
                    {
                        var todo = ToDoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                        if (todo != null)
                        {
                            todo.Title = CurrentDto.Title;
                            todo.Content = CurrentDto.Content;
                            todo.Status = CurrentDto.Status;
                        }                        
                    }
                    IsRightDrawerOpen = false;
                }
                else
                {
                    var addResult = await service.AddAsync(CurrentDto);
                    if (addResult.Status)
                    {                        
                        ToDoDtos.Add(addResult.Result);
                        IsRightDrawerOpen = false;
                    }
                }
            } catch (Exception ex) { 

            } finally {                
                UpdateLoading(false);
            }           
        }
        private async void Selected(ToDoDto dto)
        {            
            var todoResult = await service.GetFirstOfDefaultAsync(dto.Id);
            if (todoResult.Status) {
                CurrentDto = todoResult.Result;
                IsRightDrawerOpen = true;
            }
        }

        private ObservableCollection<ToDoDto> toDoDtos;
        public ObservableCollection<ToDoDto> ToDoDtos
        {
            get { return toDoDtos; }
            set { toDoDtos = value; RaisePropertyChanged(); }
        }
        void CreateToDoList() {
            for (int i = 0; i < 20; i++)
            {
                ToDoDtos.Add(new ToDoDto() { Title = "标题" + i, Content = "测试待办数据" });
            }            
        }
        
    }
}
